package com.jl.thread.lock;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.LockSupport;

/**
 * @description: 自己实现独享锁 （常用的）
 * @author: jl
 * @create: 2020/6/8 19:38
 */
public class MyLock implements Lock {

    //锁的持有者
    private AtomicReference<Thread> owner = new AtomicReference<>();

    //存放获取锁失败的线程
    private BlockingQueue<Thread> queue = new LinkedBlockingQueue<>();

    /**
     * 此方法是有可能被多个线程同时放问的，需要注意线程安全问题，此处使用了原子类，CAS底层是
     * @return
     */
    @Override
    public boolean tryLock() {
        boolean b = owner.compareAndSet(null, Thread.currentThread());
        return b;
    }


    @Override
    public void lock() {

        //默认不是伪唤醒
        boolean isFake = false;
        //当前线程获取不到锁,就一直尝试，此处需要用，需要加入等待队列
        while(!tryLock()){
            if(!isFake){//只是为了添加一遍到队列中
                queue.offer(Thread.currentThread());
                isFake = true;
                //阻塞当前线程,park方法可能会有伪唤醒，需要写在while里面
                LockSupport.park();
            }else{

            }

        }

    }

    @Override
    public void unlock() {

    }


    @Override
    public void lockInterruptibly() throws InterruptedException {

    }


    @Override
    public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
        return false;
    }


    @Override
    public Condition newCondition() {
        return null;
    }
}
